#include "EventApplication.h"

#include "EventNetwork.h"
#include "EventWindow.h"

#include <config.h>

struct _EventApplication
{
	AdwApplication parent_instance;
};

G_DEFINE_TYPE(EventApplication, event_application, ADW_TYPE_APPLICATION)

static void
event_application_finalize(GObject *object)
{
	event_object_unref(event_network);
	G_OBJECT_CLASS(event_application_parent_class)->finalize(object);
}

static void
event_application_activate(GApplication *app)
{
	GtkWindow *window;

	g_assert(EVENT_IS_APPLICATION(app));

	window = gtk_application_get_active_window(GTK_APPLICATION(app));
	if (!window) {
		window = g_object_new(EVENT_TYPE_WINDOW, "application", app,
				      NULL);
	}
	gtk_window_present(window);
}

static void
event_application_class_init(EventApplicationClass *klass)
{
	G_OBJECT_CLASS(klass)->finalize	     = event_application_finalize;
	G_APPLICATION_CLASS(klass)->activate = event_application_activate;
}

static void
event_application_about(GSimpleAction *action, GVariant *parameter,
			gpointer user_data)
{
	static const char *developers[] = { "korack/咸鱼雨涵", NULL };
	EventApplication  *self		= user_data;
	GtkWindow	  *window	= NULL;

	g_assert(EVENT_IS_APPLICATION(self));

	window = gtk_application_get_active_window(GTK_APPLICATION(self));

	adw_show_about_dialog(GTK_WIDGET(window), "application-name",
			      GETTEXT_PACKAGE, "application-icon",
			      "org.korack.event", "developer-name",
			      "Korack/咸鱼雨涵", "version", PACKAGE_VERSION,
			      "developers", developers, "copyright",
			      "© 2024 Korack/咸鱼雨涵", NULL);
}

static const GActionEntry app_actions[] = {
	{ "about", event_application_about }
};

static void
event_application_init(EventApplication *self)
{
	EventString *default_path;

	g_action_map_add_action_entries(G_ACTION_MAP(self), app_actions,
					G_N_ELEMENTS(app_actions), self);

	default_path = event_string_new(getenv("HOME"));
	event_string_append(default_path, "/.event_property.efd");
	event_network = event_network_new();
	event_network_init_all(event_network, ES_GET(default_path));
	event_debug(EventApplication, event_application_init,
		    "Property file: %s", ES_GET(default_path));
	event_object_unref(default_path);
}

EventApplication *
event_application_new(const char *id, GApplicationFlags flags)
{
	return g_object_new(EVENT_TYPE_APPLICATION, "application-id", id,
			    "flags", flags, NULL);
}
